package cn.JHai.rbac.service.imp;

import cn.JHai.rbac.RequiredPermission;
import cn.JHai.rbac.domain.Permission;
import cn.JHai.rbac.mapper.PermissionMapper;
import cn.JHai.rbac.query.PageResult;
import cn.JHai.rbac.query.QueryObject;
import cn.JHai.rbac.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionImp implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ApplicationContext ctx;

    @Override
    public int Delete(Long id) {
        return permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Permission get(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> findAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public int saveOrUpdata(Permission permission) {
        //是插入
        if(permission.getId()==null){
            return permissionMapper.insert(permission);
        }else {
            //跟新
            return permissionMapper.updateByPrimaryKey(permission);
        }
    }

    @Override
    public PageResult query(QueryObject queryObject) {

        Long count = permissionMapper.selectForCount(queryObject);
        //List<Permission> permissions =null;
        /*if(count<=3l){
            //permissions = permissionMapper.selectAll();
        }
        else{
            //permissions = permissionMapper.pageSelect(queryObject);
        }*/
        return new PageResult(queryObject.getCurrentPage(),queryObject.getPageSize(),permissionMapper.pageSelect(queryObject),count);
    }

    /**
     * 角色
     */
    @Override
    public void reload() {

        //获取数据库的内容
        List<Permission> permissions = permissionMapper.selectAll();
        //获取
        Map<String, Object> beansWithAnnotation = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> beans = beansWithAnnotation.values();
        for (Object value : beans) {

            Method[] methods = value.getClass().getMethods();

            for (Method method : methods) {
                RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);

                if(annotation != null){

                    String[] annotationValue = annotation.value();
                    Permission permission = new Permission();
                    permission.setExpression(annotationValue[1]);
                    permission.setName(annotationValue[0]);
                    if (!permissions.contains(permission))
                        permissionMapper.insert(permission);
                }
            }
        }
    }


}
